import { getTenantID, getUserID, requestFunCompon } from '@/utils';
import { message } from 'antd';
import { useMemo } from 'react';
import { useRequest } from 'umi';

// 获取详情
const getRoleByID = () => {
  const RoleDetailInfo = useRequest(
    (payload: any) => {
      let reqUrl = `/roleController/getRoleByID/${payload?.id}`;
      return requestFunCompon('GET', reqUrl);
    },
    {
      manual: true, //页面初始请求为true
      onSuccess: (res) => {
        if (!(res && res?.msgFlag)) {
          message.error(res?.msg);
        }
      },
    },
  );

  // 处理数据
  let detailInfoData = useMemo(() => {
    return RoleDetailInfo?.data?.obj;
  }, [RoleDetailInfo.data]);

  return {
    detailInfoData: detailInfoData,
    infoLoading: RoleDetailInfo.loading,
    infoRefresh: RoleDetailInfo.run,
  };
};

// 获取岗位下资源
const getResource = (stepType: string) => {
  const rseourceData = useRequest(
    () => {
      let bodyParams = {
        // positionID: getPosIDs(),
        userID: getUserID(),
        dicTypeIds: `${getTenantID()}0000`,
        pID: null,
        resourceType: null,
      };
      let reqUrl = `/roleController/getResource`;
      return requestFunCompon('POST', reqUrl, bodyParams);
    },
    {
      manual: stepType == 'roleMenu' ? false : true,
      onSuccess(data: any, params: any): void {},
    },
  );
  /* 列表数据 */
  let resourDataList = useMemo(() => {
    if (rseourceData?.data && rseourceData?.data?.msgFlag) {
      return rseourceData?.data?.obj;
    } else {
      return [];
    }
  }, [rseourceData?.data]);

  return {
    roleReload: rseourceData?.run,
    roleDataList: resourDataList,
    roleDataLoading: rseourceData.loading,
  };
};

// 授权角色 /roleController/grant
export const grantRoleCont = () => {
  const grantRole = useRequest(
    (paramsObj: any) => {
      let bodyParams = {
        ...paramsObj,
      };
      let reqUrl = `/roleController/grant`;
      return requestFunCompon('PUT', reqUrl, bodyParams);
    },
    {
      manual: true,
      onSuccess(data: any, params: any): void {},
    },
  );
  const onGrantRoleBtn = (payload: any) => {
    if (payload?.id) {
      grantRole.run(payload);
    }
  };

  /* 列表数据 */
  const grantLoading = useMemo(() => {
    return {
      grantRoleLoading: grantRole.loading ? true : false,
    };
  }, [grantRole.loading]);
  return {
    onGrantRoleBtn,
    grantLoading,
  };
};

export { getRoleByID, getResource };
